//
//  MYPersonalInfoViewController.m
//  投融保
//
//  Created by 523 on 13-12-17.
//  Copyright (c) 2013年 木叶科技. All rights reserved.
//

#import "MYPersonalInfoViewController.h"

#import "bindBankCard.h"
#import "MYWebService.h"
#import "MYLoginViewController.h"
#import "MBProgressHUD.h"

@interface MYPersonalInfoViewController (){
    
    NSMutableArray *imageArray;
}

@end

@implementation MYPersonalInfoViewController
@synthesize scrollView;
@synthesize serviceUploadFrontImage;
@synthesize serViceUpLoadBackImage;
@synthesize serViceCertified,serViceCertifiedNotifi;

@synthesize arrImageReturnedPath;
@synthesize imagePcik1,imagePcik2;

@synthesize actionSheet1,actionSheet2;

extern NSString *realName; //真实姓名
extern NSString *key;
extern NSString *appKey;
extern NSDictionary *userInformation ;//用户信息

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //初始化 上传图片数组
    imageArray=[NSMutableArray new];
    
    int _Y=250;
    if (SCREEN_HEIGHT>480) {
        _Y=80;
    }
    
    UITapGestureRecognizer *gesture=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyBoard)];
    [self.scrollView setContentSize:CGSizeMake(SCREEN_WIDTH, 1400)];//740
    [self.scrollView addGestureRecognizer:gesture];
    [self.scrollView setShowsVerticalScrollIndicator:NO];
    self.btnlongTime.selected=NO; // 有效时间
    self.serviceUploadFrontImage =[MYWebService new];
    self.serViceUpLoadBackImage =[MYWebService new];
    //判断如果用户已登录，并绑定：
    if ([[userInformation valueForKey:@"realNameStatus"] isEqualToString:@"IS"]||[[userInformation valueForKey:@"realNameStatus"] isEqualToString:@"IN"])
    {
        self.txtRealName.text=[userInformation valueForKey:@"realName"];
        self.txtIdNo.text=[userInformation valueForKey:@"certNo"];
        if ([[userInformation valueForKey:@"cardOff"]isEqualToString:@"longTime"]) {
            self.btnlongTime.selected=YES;
        }else
        {
            self.txtDate.text=[userInformation valueForKey:@"cardOff"];
        }
        //        NSLog(@"%@",[userInformation valueForKey:@"certFrontPath"]);
        //        if (![[userInformation valueForKey:@"certFrontPath"] isEqual:[NSNull null]]) {
        //             [self.btnFrontImage setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[userInformation valueForKey:@"certFrontPath"]]]] forState:UIControlStateNormal];
        //        }
        
        
        
        //        if (![[userInformation valueForKey:@"certBackPath"] isEqual:[NSNull null]]) {
        //            [self.btnFrontImage setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[userInformation valueForKey:@"certBackPath"]] options:NSDataReadingMappedIfSafe error:Nil]] forState:UIControlStateNormal];
        //        }
        self.scrollView.userInteractionEnabled=YES;
    }else if([[userInformation valueForKey:@"realNameStatus"] isEqualToString:@"N"]||[[userInformation valueForKey:@"realNameStatus"] isEqualToString:@"NO"])
    {
        //如果未认证或认证失败
        self.txtRealName.text=[userInformation valueForKey:@"realName"];
    }else
    {
        //如果用户是来自注册流程
        self.txtRealName.text=realName;
    }
    
    UIDatePicker *datePicker=[UIDatePicker new];
    // 设置显示中文
    datePicker.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    // 只显示年月日
    datePicker.datePickerMode = UIDatePickerModeDate;
    // 添加值改变的监听器
    [datePicker addTarget:self action:@selector(birthdayChange:) forControlEvents:UIControlEventValueChanged];
    [self.txtDate setInputView:datePicker];
    
    //身份证是否长期有效选择按钮背景
    [self.btnlongTime setImage:[UIImage imageNamed:@"disagreed_icon"] forState:UIControlStateNormal];
    [self.btnlongTime setImage:[UIImage imageNamed:@"agreed_icon"] forState:UIControlStateSelected];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (IBAction)btnDateChooseAction:(UIButton *)sender {
    if (sender.selected) {
        [self.view endEditing:YES];
        sender.selected=!sender.selected;
        return;
    }else{
        
        [self.txtDate becomeFirstResponder];
        sender.selected=!sender.selected;
        return;
    }
    
}

- (IBAction)uploadPic:(UIButton *)sender {
    
    
    switch (sender.tag) {
        case 10109:
        {
            actionSheet1=[[UIActionSheet alloc]  initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"相机" otherButtonTitles:@"相册",@"图片库", nil];
            [actionSheet1 setActionSheetStyle:UIActionSheetStyleDefault];
            [actionSheet1 showInView:self.view];
            //            imagePcik1=[[UIImagePickerController alloc] init];
            //            [imagePcik1 setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            //            [imagePcik1 setDelegate:self];
            //            [self presentViewController:imagePcik1 animated:NO completion:^{
            //
            //                [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
            //            }];
        }
            break;
        case 10119:
        {
            actionSheet2=[[UIActionSheet alloc]  initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"相机" otherButtonTitles:@"相册",@"图片库", nil];
            [actionSheet2 setActionSheetStyle:UIActionSheetStyleDefault];
            [actionSheet2 showInView:self.view];
        }
            break;
        default:
            break;
    }
    
}

- (IBAction)idDateChooseAction:(UIButton *)sender {
    if (sender.selected) {
        sender.selected=!sender.selected;
        [sender setImage:[UIImage imageNamed:@"disagreed_icon"] forState:UIControlStateNormal];
        return;
    }else
    {
        sender.selected=!sender.selected;
        [sender setImage:[UIImage imageNamed:@"agreed_icon"] forState:UIControlStateSelected];
        return;
    }
}



//更新实名信息
- (IBAction)btnSubmitClick:(UIButton *)sender {
    //    //更新实名认证信息
    //        NSString *strUpdateRealNameInfoService=@"service=updateRealNameInfoService&realName=新疆&certNo=500233198810291031&cardOff=2013-12-20&certFrontPath=pangran&certBackPath=pangran";
    if (imageArray.count<2) {
        UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:@"信息不完整" message:@"请提交正反两面身份证照片" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [myAlert show];
    }else{
        self.serViceCertified=[MYWebService new];
        
        //上传图片到服务器服务器，返回图片地址，提交实名认证的时候需要将返回的服务器地址传过去。
        //更新实名认证信息
        //判断身份正有效时间
        NSString *cardOff;
        if (self.btnlongTime.selected) {
            cardOff=@"longTime";
        }else
        {
            cardOff=self.txtDate.text;
        }
        
        NSString *strUpdateRealNameInfoService=[NSString stringWithFormat:@"service=updateRealNameInfoService&realName=%@&certNo=%@&cardOff=%@&certFrontPath=%@&certBackPath=%@",self.txtRealName.text,self.txtIdNo.text,cardOff,[[self.serviceUploadFrontImage.profileDataSyn valueForKey:@"result"] valueForKey:@"filePath"],[[self.serViceUpLoadBackImage.profileDataSyn valueForKey:@"result"] valueForKey:@"filePath"]];
        
        
        MBProgressHUD *mbHud = [[MBProgressHUD alloc] initWithView:self.view];
        
        mbHud.labelText = @"正在更新";
        [self.view addSubview:mbHud];
        [mbHud showAnimated:YES whileExecutingBlock:^{
            //z菊花转动的时候 开始加载数据
            [self.serViceCertified getDataSynWithKey:key encryptedString:strUpdateRealNameInfoService appKey:appKey];
            
        } completionBlock:^{
            //执行加载数据完成后的操作。
            if ([[[self.serViceCertified.profileDataSyn valueForKey:@"result"] valueForKey:@"code"] intValue]==1) {
                self.serViceCertifiedNotifi=[MYWebService new];
                //如果实名更新成功 发送实名认证
                NSString *strSendRealNameService=@"service=sendRealNameService";
                [self.serViceCertifiedNotifi getDataSynWithKey:key encryptedString:strSendRealNameService appKey:appKey];
                //判断是否发送实名认证信息成功
//                NSLog(@"%d-------%@",[[[self.serViceCertifiedNotifi.profileDataSyn valueForKey:@"result"] valueForKey:@"code"]intValue],userInformation);
                if ([[[self.serViceCertifiedNotifi.profileDataSyn valueForKey:@"result"] valueForKey:@"code"]intValue]==1&&!userInformation){
//                    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:[[self.serViceCertifiedNotifi getDataSynWithKey:key encryptedString:strSendRealNameService appKey:appKey] valueForKey:@"message"] delegate:self cancelButtonTitle:@"立即登录" otherButtonTitles:nil, nil];
//                    [alert show];
                    MBProgressHUD *mbHud=[MBProgressHUD new];
                    mbHud.labelText=@"实名认证已提交";
                    [mbHud setMode:MBProgressHUDModeText];
                    [self.view addSubview:mbHud];
                    [mbHud showAnimated:YES whileExecutingBlock:^{
                        sleep(1);
                    } completionBlock:^{
                        [mbHud removeFromSuperview];
                        bindBankCard *bindVc= [bindBankCard new];
                        [self presentViewController:bindVc animated:NO completion:nil];
                    }];
                    
                }else{
                    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:[[self.serViceCertifiedNotifi getDataSynWithKey:key encryptedString:strSendRealNameService appKey:appKey] valueForKey:@"message"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alert show];

                }
                
                //            NSLog(@"发送实名信息结果：%@",serViceCertifiedNotifi.profileDataSyn);
                
            }else if([[[self.serViceCertified.profileDataSyn valueForKey:@"result"] valueForKey:@"code"] intValue]==0)
            {
                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:@"输入信息或网络异常" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
            }
  
        }];  //block结束
        
    }

}

//返回事件
- (IBAction)btnReturnClick:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark -----图片选择回调---------

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    if (picker==imagePcik1) {
        //回调方法中获取用户选择的图片
        UIImage *shenFenImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        NSData *imageData = UIImageJPEGRepresentation(shenFenImage, 0.1);//压缩图片为data；
        NSString *tempPath=[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"shenfenzheng_Front.png"];
        [imageData writeToFile:tempPath atomically:NO];
        [imageArray addObject:imageData];
        
        MBProgressHUD *mbHud = [[MBProgressHUD alloc] initWithView:self.view];
        mbHud.labelText = @"正在上传";
        [self.view addSubview:mbHud];
        [mbHud showAnimated:YES whileExecutingBlock:^{
            //z菊花转动的时候 开始加载数据
            NSString *strAppFileUploadService=[NSString stringWithFormat:@"service=appFileUploadService&file=%@&fileExt=.png",[imageData stringWithHexBytes1]];
            [self.serviceUploadFrontImage getDataSynWithKey:key encryptedString:strAppFileUploadService appKey:nil];
            
        } completionBlock:^{
            //执行加载数据完成后的操作。
            [mbHud removeFromSuperview];
            NSString *strMessage;
            if ([[[self.serviceUploadFrontImage.profileDataSyn valueForKey:@"result"] valueForKey:@"code"] intValue]==1) {
                strMessage=[[self.serviceUploadFrontImage.profileDataSyn valueForKey:@"result"] valueForKey:@"message"];
            }else
            {
                strMessage=[[self.serviceUploadFrontImage.profileDataSyn valueForKey:@"result"] valueForKey:@"message"];
            }
            [self.btnFrontImage setImage:[UIImage imageWithContentsOfFile:tempPath] forState:UIControlStateNormal];
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:strMessage delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }];
        
        [self dismissViewControllerAnimated:NO completion:^{//2.关闭这个模态视图回到之前的view
            if (IOS_VERSION>=7.0) {
                [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent];
            }
        }];
        
        
    }else
    {
        //回调方法中获取用户选择的图片
        
        
        
        UIImage *shenFenImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        NSData *imageData = UIImageJPEGRepresentation(shenFenImage, 0.1);//压缩图片为data；
        NSString *tempPath=[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"shenfenzheng_Back.png"];
        [imageData writeToFile:tempPath atomically:NO];
        [imageArray addObject:imageData];
        
        MBProgressHUD *mbHud = [[MBProgressHUD alloc] initWithView:self.view];
        mbHud.labelText = @"正在上传";
        [self.view addSubview:mbHud];
        [mbHud showAnimated:YES whileExecutingBlock:^{
            //z菊花转动的时候 开始加载数据
            NSString *strAppFileUploadService=[NSString stringWithFormat:@"service=appFileUploadService&file=%@&fileExt=.png",[imageData stringWithHexBytes1]];
            [self.serViceUpLoadBackImage getDataSynWithKey:key encryptedString:strAppFileUploadService appKey:nil];
            
        } completionBlock:^{
            //执行加载数据完成后的操作。
            [mbHud removeFromSuperview];
            NSString *strMessage;
            if ([[[self.serViceUpLoadBackImage.profileDataSyn valueForKey:@"result"] valueForKey:@"code"] intValue]==1) {
                strMessage=[[self.serViceUpLoadBackImage.profileDataSyn valueForKey:@"result"] valueForKey:@"message"];
            }else{
                strMessage=[[self.serViceUpLoadBackImage.profileDataSyn valueForKey:@"result"] valueForKey:@"message"];
            }
            [self.btnBackImage setImage:[UIImage imageWithContentsOfFile:tempPath] forState:UIControlStateNormal];
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:strMessage delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }];
        
        [self dismissViewControllerAnimated:NO completion:^{//2.关闭这个模态视图回到之前的view
            if (IOS_VERSION>=7.0) {
                [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent];
            }
        }];
        
    }
    
    
    
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:NO completion:^{//2.关闭这个模态视图
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent];
    }];
}

- (void)closeKeyBoard
{
    [self.view endEditing:YES];
}

#pragma mark ---------uitextFiled----------

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    
}



#pragma mark 监听日期选择控件的改变
- (void)birthdayChange:(UIDatePicker *)picker {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    self.txtDate.text = [formatter stringFromDate:picker.date];
}

#pragma mark 返回NO代表不允许手动改变文本框的文本
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // 只有生日和性别才不允许修改文字
    return !(textField == self.txtDate);
}

#pragma mark ----------alertView delegate---------------
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    switch (buttonIndex) {
        case 0:
            //            [self presentModalViewController:[MYLoginViewController new] animated:NO];
            [self presentViewController:[MYLoginViewController new] animated:YES completion:nil];
            break;
        default:
            break;
    }
}

#pragma mark --------------actionsheet------------
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet==actionSheet1) {
        imagePcik1=[[UIImagePickerController alloc] init];
        switch (buttonIndex) {
            case 0:
                [imagePcik1 setSourceType:UIImagePickerControllerSourceTypeCamera];
                break;
            case 1:
                //相册
                [imagePcik1 setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
                break;
            case 2:
                //图片库
                [imagePcik1 setSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
                break;
            default:
                break;
        }
        [imagePcik1 setDelegate:self];
        [self presentViewController:imagePcik1 animated:NO completion:^{
            [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
        }];
        
    }else
    {
        imagePcik2=[[UIImagePickerController alloc] init];
        switch (buttonIndex) {
            case 0:
                //相机
                [imagePcik2 setSourceType:UIImagePickerControllerSourceTypeCamera];
                break;
            case 1:
                
                
                [imagePcik2 setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
                
                break;
            case 2:
                
                //图片库
                [imagePcik2 setSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
                break;
            default:
                break;
        }
        [imagePcik2 setDelegate:self];
        [self presentViewController:imagePcik2 animated:NO completion:^{
            
            [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
        }];
        
        
    }
    
}


#pragma mark-   -----------状态栏底色------
- (UIStatusBarStyle)preferredStatusBarStyle
{
    [self.view setBackgroundColor:[UIColor blackColor]];
    return UIStatusBarStyleLightContent;
}
- (BOOL)prefersStatusBarHidden
{
    return NO;
}

@end
